package com.fjut.kms.dao;

import com.fjut.kms.domain.UserActRecord;
import com.fjut.kms.tools.DBTools;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Empathy on 2017/7/30.
 */
public class UserActRecordJDBCImpl implements UserActRecordDao {
    private static final String SQL_ADD_USERACTSOFT="insert into userActRecord values(null,?,?,?,?,?,?,?,?,?)";
    private static final String GET_ACTSOFT_BYUSERNAME_SOFTNAME="select * from userActRecord where userName=? and softName=? order by reqDate desc";
    public void addUserActRecord(UserActRecord uar){
        Connection conn= DBTools.getConn();
        PreparedStatement pstmt=null;
        try{
            pstmt =conn.prepareStatement(SQL_ADD_USERACTSOFT);
            pstmt.setString(1,uar.getSoftName());
            pstmt.setString(2,uar.getUserName());
            pstmt.setString(3,uar.getReqDate());
            pstmt.setString(4,uar.getStatus());
            pstmt.setString(5,uar.getIp());
            pstmt.setString(6,uar.getMac());
            pstmt.setString(7,uar.getMachineId());
            pstmt.setString(8,uar.getErrCode());
            pstmt.setString(9,uar.getOs());
            pstmt.executeUpdate();
        } catch (SQLException e){
            e.printStackTrace();
        }finally {
            DBTools.releaseRes(conn,pstmt,null);
        }
    }

    public List<UserActRecord> getUserActRecordBySoftName(String userName,String softName){
        Connection conn= DBTools.getConn();
        PreparedStatement pstmt=null;
        ResultSet rset=null;
        List<UserActRecord> uarList=new ArrayList<UserActRecord>();
        try{
            pstmt=conn.prepareStatement(GET_ACTSOFT_BYUSERNAME_SOFTNAME);
            pstmt.setString(1,userName);
            pstmt.setString(2,softName);
            rset=pstmt.executeQuery();
            while (rset.next()){
                UserActRecord uar=new UserActRecord();
                uar.setSoftName(rset.getString("softName"));
                uar.setUserName(rset.getString("userName"));
                uar.setStatus(rset.getString("status"));
                uar.setIp(rset.getString("ip"));
                uar.setReqDate(rset.getString("reqDate"));
                uar.setErrCode(rset.getString("errCode"));
                uarList.add(uar);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            DBTools.releaseRes(conn,pstmt,null);
        }
        return uarList.size()>0?uarList:null;
    }
}
